
var DATA = {

    per_page : 2,

    page : 1

};

var _Global_Data = {

    list_info : DATA,

    replenishment_info : {

        account : '',

        password : '',

        name : '',

        phone : '',

        customer_address_id : ''
    },                                //绑定的补货员信息

    replenishment_edit : {},            //编辑补货员信息存储

    replenishment_clerks : {},       //本地存储的补货员列表

    map_address : {

        province : '',

        city : '',

        district : '',

        address : '',

        longitude : '',

        latitude : ''

    },                              //地图选址信息

    address_lists : []             //本地存储的地址列表

};

//补货员
var ReplenishmentSoruce = new Resource( API_LIST.REPLENISHMENT_HANDLE , Vue.http );

//领货地址
var AddressSoruce = new Resource( API_LIST.NEW_ADDRESS , Vue.http );

// 定义一个地图对象
var map;
// 创建一个标注
var marker;

!function(){

    var vm = new Vue({

        el : '#replenishment',

        data : _Global_Data,

        created : function(){

            this.initData();

            this.getAddressLIst();

        },

        computed : {

            addressStitch : function addressStitch(){

                return this.map_address.province + this.map_address.city + this.map_address.district + this.map_address.address;

            }

        },

        methods : {
            //select2获取value的方法
            getValue : function getSelectValue(e){

                this.replenishment_info[e.target.dataset.name] = e.target.value;

            },
            //改变页数的时候出发的函数
            pageChange : function pageChange(val){

                this.list_info.page = val;

                this.initData();

            },
            //重置地图
            resetMap : function resetMap(){

                map.reset();

            },
            //重置输入框的值
            clearValue : function clearValue(){

                this.replenishment_info.account = '';

                this.replenishment_info.password = '';

                this.replenishment_info.name = '';

                this.replenishment_info.phone = '';

                this.replenishment_info.customer_address_id = '';

                $('.select2_category').val('').trigger('change');

            },
            //点击查看，修改补货员信息
            editReplenishment : function editReplenishment(id){

                var self = this;

                App.blockUI('#editor-form');

                ReplenishmentSoruce.edit(id)
                                    .then(function(res){

                                        if( parseInt(res.data.code) === 0 ){

                                            self.replenishment_edit = res.data.replenishment_clerk;

                                            self.replenishment_info.account = res.data.replenishment_clerk.account;

                                            self.replenishment_info.name = res.data.replenishment_clerk.name;

                                            self.replenishment_info.phone = res.data.replenishment_clerk.phone;

                                            if( !res.data.replenishment_clerk.address ) {

                                                App.unblockUI('#editor-form');

                                                return;

                                            }

                                            self.replenishment_info.customer_address_id = res.data.replenishment_clerk.address.customer_address_id;

                                            $('.select2_category').val(self.replenishment_info.customer_address_id).trigger('change');

                                        }else{

                                            alert(res.data.error);

                                        }

                                        App.unblockUI('#editor-form');

                                    })
                                    .catch(function(err){

                                        console.log(err);

                                        App.unblockUI('#editor-form');

                                        alert('网络异常，请重试！');

                                    })

            },
            //删除补货员信息
            deleteReplenishment : function deleteReplenishment(id){

                if( !confirm('是否删除该补货员信息？') ) return false;

                var self = this;

                App.blockUI('#table_form');

                ReplenishmentSoruce.destroy(id)
                                    .then(function(res){

                                        if( parseInt(res.data.code) === 0 ){

                                            App.unblockUI('#table_form');

                                            self.initData();

                                            alert('删除成功！');

                                        }else{

                                            App.unblockUI('#table_form');

                                            alert(res.data.error);

                                        }

                                    })
                                    .catch(function(err){

                                        console.log(err);

                                        App.unblockUI('#table_form');

                                        alert('网络异常，请重试！');

                                    })

            },
            //更新补货员信息
            updateReplenishment : function updateReplenishment(){

                var self = this;

                App.blockUI('#editor-form');

                ReplenishmentSoruce.update( self.replenishment_edit.id , self.replenishment_info )
                                    .then(function(res){

                                        if( parseInt(res.data.code) === 0 ){

                                            self.initData();

                                            App.unblockUI('#editor-form');

                                            self.clearValue();

                                            $('.close').trigger('click');

                                        }else{

                                            App.unblockUI('#editor-form');

                                            alert(res.data.error);

                                        }

                                    })
                                    .catch(function(err){

                                        console.log(err);

                                        App.unblockUI('#editor-form');

                                        alert('网络异常，请重试！');

                                    })

            },
            //提交保存补货员信息
            confirmPost : function confirmPost(){

                var self = this;

                App.blockUI('#staff_form');

                ReplenishmentSoruce.store( this.replenishment_info )
                                    .then(function(res){

                                        if(parseInt( res.data.code) === 0 ){

                                            self.initData();

                                            self.clearValue();

                                            App.unblockUI('#staff_form');

                                            alert('提交成功！');

                                        }else {

                                            App.unblockUI('#staff_form');

                                            alert(res.data.error);

                                        }

                                    })
                                    .catch(function(err){

                                        console.log(err);

                                        App.unblockUI('#staff_form');

                                        alert('网络异常，请重试！');

                                    })

            },
            //新增保存领货地址
            addNewAddress : function addNewAddress(){

                var self = this;

                App.blockUI('#map_form');

                AddressSoruce.store( self.map_address )
                            .then(function(res){

                                if( parseInt(res.data.code) === 0 ){

                                    alert('新增成功！');

                                    self.getAddressLIst();

                                }else {

                                    alert(res.data.error);

                                }

                                App.unblockUI('#map_form');

                            })
                            .catch(function(err){

                                console.log(err);

                                App.unblockUI('#map_form');

                                alert('网络异常，请重试！');

                            })
            },
            //获取现有地址列表
            getAddressLIst : function getAddressLIst(){

                var self = this;

                App.blockUI('#address_form');

                ReplenishmentSoruce.create()
                                .then(function(res){

                                    if( parseInt(res.data.code) === 0 ){

                                        self.address_lists = res.data.customer_addresses

                                    }else {

                                        alert(res.data.error);

                                    }

                                    App.unblockUI('#address_form');

                                })
                                .catch(function(err){

                                    console.log(err);

                                    App.unblockUI('#address_form');

                                    alert('网络异常，请重试！');

                                })

            },
            //删除地址
            deleteAddress : function deleteAddress( id ){

                if( !confirm('是否删除该地址？') ) return false;

                var self = this;

                App.blockUI('#address_form');

                ReplenishmentSoruce.show( id )
                                .then(function(res){

                                    if( parseInt(res.data.code) === 0 ){

                                        alert('删除成功！');

                                        self.getAddressLIst();

                                    }else {

                                        alert(res.data.error);

                                    }

                                    App.unblockUI('#address_form');

                                })
                                .catch(function(err){

                                    console.log(err);

                                    App.unblockUI('#address_form');

                                    alert('网络异常，请重试！');

                                })

            },
            //获取补货员列表
            initData : function initData(){

                var self = this;

                App.blockUI('#table_form');

                ReplenishmentSoruce.index(self.list_info)
                                    .then(function(res){

                                        if(parseInt(res.data.code) === 0){

                                            self.replenishment_clerks = res.data.replenishment_clerks;

                                            self.replenishment_clerks.per_page = parseInt(self.replenishment_clerks.per_page);

                                            App.unblockUI('#table_form');

                                        }else {

                                            App.unblockUI('#table_form');

                                            alert(res.data.error);

                                        }

                                    })
                                    .catch(function(err){

                                        console.log(err);

                                        App.unblockUI('#table_form');

                                        alert('网络异常，请重试！');

                                    })

            }

        }

    });

}();


function initMap(){

    setTimeout(function(){

        createMap();

        setMapEvents();

    },30);

}

function G(id) {
    return document.getElementById(id);
}

//创建地图
function createMap(){

    map = new BMap.Map("map_container");

    var geolocation = new BMap.Geolocation();

    geolocation.getCurrentPosition(function(GeolocationResult){

        if(this.getStatus() == BMAP_STATUS_SUCCESS){

            var point = new BMap.Point(GeolocationResult.point.lng,GeolocationResult.point.lat);

            map.centerAndZoom(point,19);

            setMarker(point);

            address();

            //点击地图更换标注
            map.addEventListener("click",function(e){

                //清楚所有标注
                map.clearOverlays();

                var point1 = new BMap.Point(e.point.lng,e.point.lat);

                setMarker(point1);

                address();

            });

        }
        else {

            alert('failed'+this.getStatus());

        }
    },{enableHighAccuracy: true});

}

//设置marker的方法
function setMarker( point ){

    marker = new BMap.Marker(point);

    map.addOverlay(marker);                     // 将标注添加到地图中

    marker.setAnimation(BMAP_ANIMATION_BOUNCE); //跳动的动画

    var label = new BMap.Label("当前位置",{offset:new BMap.Size(20,-20)});

    marker.setLabel(label);

}

//地址解析
function address(){

    var geoc = new BMap.Geocoder();

    var point = marker.getPosition();

    _Global_Data.map_address.longitude = point.lng;

    _Global_Data.map_address.latitude = point.lat;

    geoc.getLocation(point,function(res){

        _Global_Data.map_address.province = res.addressComponents.province;

        _Global_Data.map_address.city = res.addressComponents.city;

        _Global_Data.map_address.district = res.addressComponents.district;

        _Global_Data.map_address.address = res.addressComponents.street;

    })

}

//设置地图事件
function setMapEvents(){

    map.enableScrollWheelZoom();

    map.enableInertialDragging();

}

//设置搜索
var ac = new BMap.Autocomplete(    //建立一个自动完成的对象
    {"input" : "suggestId"
        ,"location" : map
    });

ac.addEventListener("onhighlight", function(e) {  //鼠标放在下拉列表上的事件
    var str = "";
    var _value = e.fromitem.value;
    var value = "";
    if (e.fromitem.index > -1) {
        value = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
    }
    str = "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value;

    value = "";
    if (e.toitem.index > -1) {
        _value = e.toitem.value;
        value = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
    }
    str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value;
    G("searchResultPanel").innerHTML = str;
});

var myValue;

ac.addEventListener("onconfirm", function(e) {    //鼠标点击下拉列表后的事件

    var _value = e.item.value;

    myValue = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;

    G("searchResultPanel").innerHTML ="onconfirm<br />index = " + e.item.index + "<br />myValue = " + myValue;

    setPlace();
});

function setPlace(){

    map.clearOverlays();    //清除地图上所有覆盖物

    function myFun(){

        var pp = local.getResults().getPoi(0).point;    //获取第一个智能搜索的结果

        map.centerAndZoom(pp, 18);

        setMarker(pp);

    }

    var local = new BMap.LocalSearch(map, { //智能搜索

        onSearchComplete: myFun

    });

    local.search(myValue);

}